

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head><!-- hexo injector head_begin start --><link rel="stylesheet" href="/css/my-avatar.css"><!-- hexo injector head_begin end -->
  <meta charset="UTF-8">

  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/icon/coffee.png">
  

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="晓寒">
  <meta name="keywords" content="">
  
    <meta name="description" content="通过STM32CubeMX快速开发流水灯程序，后面的实践是为23届大一准备">
<meta property="og:type" content="article">
<meta property="og:title" content="STM32流水灯">
<meta property="og:url" content="http://example.com/posts/2680/index.html">
<meta property="og:site_name" content="Xiaohan&#96;s Blog">
<meta property="og:description" content="通过STM32CubeMX快速开发流水灯程序，后面的实践是为23届大一准备">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/posts/2680/img20230913152634.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913152746.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913152822.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913152948.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153027.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153117.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153155.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153352.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153428.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153449.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913153556.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913154550.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913154136.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913154209.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913154759.png">
<meta property="og:image" content="http://example.com/posts/2680/img20230913154818.png">
<meta property="article:published_time" content="2023-10-25T13:29:46.000Z">
<meta property="article:modified_time" content="2025-03-05T04:37:23.339Z">
<meta property="article:author" content="晓寒">
<meta property="article:tag" content="单片机入门">
<meta property="article:tag" content="STM32">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/posts/2680/img20230913152634.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>STM32流水灯 - Xiaohan`s Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1749284_5i9bdhy70f8.css">



<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1736178_k526ubmyhba.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="/css/mac.css">
<link rel="stylesheet" href="/css/shubiao.css">
<link rel="stylesheet" href="/css/huadong.css">
<link rel="stylesheet" href="/css/fonts.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.8","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":true,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false},"umami":{"src":null,"website_id":null,"domains":null,"start_time":"2024-01-01T00:00:00.000Z","token":null,"api_server":null}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><style>mjx-container[jax="SVG"] {
  direction: ltr;
}

mjx-container[jax="SVG"] > svg {
  overflow: visible;
}

mjx-container[jax="SVG"][display="true"] {
  display: block;
  text-align: center;
  margin: 1em 0;
}

mjx-container[jax="SVG"][justify="left"] {
  text-align: left;
}

mjx-container[jax="SVG"][justify="right"] {
  text-align: right;
}

g[data-mml-node="merror"] > g {
  fill: red;
  stroke: red;
}

g[data-mml-node="merror"] > rect[data-background] {
  fill: yellow;
  stroke: none;
}

g[data-mml-node="mtable"] > line[data-line] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > rect[data-frame] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > .mjx-dashed {
  stroke-dasharray: 140;
}

g[data-mml-node="mtable"] > .mjx-dotted {
  stroke-linecap: round;
  stroke-dasharray: 0,140;
}

g[data-mml-node="mtable"] > svg {
  overflow: visible;
}

[jax="SVG"] mjx-tool {
  display: inline-block;
  position: relative;
  width: 0;
  height: 0;
}

[jax="SVG"] mjx-tool > mjx-tip {
  position: absolute;
  top: 0;
  left: 0;
}

mjx-tool > mjx-tip {
  display: inline-block;
  padding: .2em;
  border: 1px solid #888;
  font-size: 70%;
  background-color: #F8F8F8;
  color: black;
  box-shadow: 2px 2px 5px #AAAAAA;
}

g[data-mml-node="maction"][data-toggle] {
  cursor: pointer;
}

mjx-status {
  display: block;
  position: fixed;
  left: 1em;
  bottom: 1em;
  min-width: 25%;
  padding: .2em .4em;
  border: 1px solid #888;
  font-size: 90%;
  background-color: #F8F8F8;
  color: black;
}

foreignObject[data-mjx-xml] {
  font-family: initial;
  line-height: normal;
  overflow: visible;
}

.MathJax path {
  stroke-width: 3;
}

mjx-container[display="true"] {
  overflow: auto hidden;
}

mjx-container[display="true"] + br {
  display: none;
}
</style></head>


<body><!-- hexo injector body_begin start --><div id="web_bg"></div><!-- hexo injector body_begin end -->
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Xiaohan`s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>Home</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>Category</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>Tag</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>Archive</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/" target="_self">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>About</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/bg/mountains.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="STM32流水灯"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-10-25 21:29" pubdate>
          2023年10月25日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          2.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          18 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">STM32流水灯</h1>
            
              <p id="updated-time" class="note note-info" style="">
                
                  
                    本文最后更新于 2025年3月5日 下午
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h2 id="stm32cubemx的配置">STM32CubeMX的配置</h2>
<ul>
<li>创建STM32CubeMX工程</li>
</ul>
<p><img src="img20230913152634.png" srcset="/img/loading.gif" lazyload></p>
<ul>
<li><p>打开外部晶振 <img src="img20230913152746.png" srcset="/img/loading.gif" lazyload></p></li>
<li><p>时钟树设置
注意外部晶振的频率是由硬件决定的，选择与硬件相匹配的频率 <img src="img20230913152822.png" srcset="/img/loading.gif" lazyload></p></li>
<li><p>配置IO引脚 <img src="img20230913152948.png" srcset="/img/loading.gif" lazyload></p></li>
<li><p>配置文件路径和代码生成 <img src="img20230913153027.png" srcset="/img/loading.gif" lazyload></p></li>
</ul>
<p><img src="img20230913153117.png" srcset="/img/loading.gif" lazyload></p>
<ul>
<li>生成代码 <img src="img20230913153155.png" srcset="/img/loading.gif" lazyload></li>
</ul>
<h2 id="keil配置">KEIL配置</h2>
<p>下面的工具栏在页面的左上角</p>
<p><img src="img20230913153352.png" srcset="/img/loading.gif" lazyload></p>
<p>点击红色方框中的按钮</p>
<p><img src="img20230913153428.png" srcset="/img/loading.gif" lazyload></p>
<p><img src="img20230913153449.png" srcset="/img/loading.gif" lazyload></p>
<p>选择你用的烧录器，点击右边的setting后可以看到芯片是否连接成功</p>
<p><img src="img20230913153556.png" srcset="/img/loading.gif" lazyload></p>
<p>由于hal库函数中HAL_Delay()函数使用的是系统时钟的中断来实现的，容易进入死循环或者程序卡死，因此使用非中断实现延时，在工程中加入delay.c和delay.h定义了函数Delay_ms()和Delay_us()来实现。下面是在工程中加入文件的指南。</p>
<p>将Delay文件夹加入文件目录</p>
<p><img src="img20230913154550.png" srcset="/img/loading.gif" lazyload></p>
<p><img src="img20230913154136.png" srcset="/img/loading.gif" lazyload></p>
<p><img src="img20230913154209.png" srcset="/img/loading.gif" lazyload></p>
<p>点击add file将delay.c文件加入，并将delay文件夹加入include路径</p>
<p><img src="img20230913154759.png" srcset="/img/loading.gif" lazyload></p>
<p><img src="img20230913154818.png" srcset="/img/loading.gif" lazyload></p>
<ul>
<li>编写程序</li>
</ul>
<p>注意自己的代码都要写在USER_CODE_BEGIN...和USER_CODE_END...注释之间，否则使用STM32CubeMX重新generate的时候自己的代码会被清除。</p>
<p>自己定义的端口名称会在main.h中生成(STM32CubeMX自动生成)，这里是我定义的端口</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/* Private defines -----------------------------------------------------------*/</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED1_Pin GPIO_PIN_6</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED1_GPIO_Port GPIOB</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED2_Pin GPIO_PIN_7</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED2_GPIO_Port GPIOB</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED3_Pin GPIO_PIN_8</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED3_GPIO_Port GPIOB</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED4_Pin GPIO_PIN_9</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> LED4_GPIO_Port GPIOB</span><br></code></pre></td></tr></table></figure>
<p>为了方便找到位置这里将main.c都列出，加上的代码边上都有注释</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/* USER CODE BEGIN Header */</span><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">  ******************************************************************************</span><br><span class="hljs-comment">  * @file           : main.c</span><br><span class="hljs-comment">  * @brief          : Main program body</span><br><span class="hljs-comment">  ******************************************************************************</span><br><span class="hljs-comment">  * @attention</span><br><span class="hljs-comment">  *</span><br><span class="hljs-comment">  * Copyright (c) 2023 STMicroelectronics.</span><br><span class="hljs-comment">  * All rights reserved.</span><br><span class="hljs-comment">  *</span><br><span class="hljs-comment">  * This software is licensed under terms that can be found in the LICENSE file</span><br><span class="hljs-comment">  * in the root directory of this software component.</span><br><span class="hljs-comment">  * If no LICENSE file comes with this software, it is provided AS-IS.</span><br><span class="hljs-comment">  *</span><br><span class="hljs-comment">  ******************************************************************************</span><br><span class="hljs-comment">  */</span><br><span class="hljs-comment">/* USER CODE END Header */</span><br><span class="hljs-comment">/* Includes ------------------------------------------------------------------*/</span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"main.h"</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"gpio.h"</span></span><br><br><span class="hljs-comment">/* Private includes ----------------------------------------------------------*/</span><br><span class="hljs-comment">/* USER CODE BEGIN Includes */</span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"delay.h"</span></span><br><span class="hljs-comment">/* USER CODE END Includes */</span><br><br><span class="hljs-comment">/* Private typedef -----------------------------------------------------------*/</span><br><span class="hljs-comment">/* USER CODE BEGIN PTD */</span><br><br><span class="hljs-comment">/* USER CODE END PTD */</span><br><br><span class="hljs-comment">/* Private define ------------------------------------------------------------*/</span><br><span class="hljs-comment">/* USER CODE BEGIN PD */</span><br><span class="hljs-comment">/* USER CODE END PD */</span><br><br><span class="hljs-comment">/* Private macro -------------------------------------------------------------*/</span><br><span class="hljs-comment">/* USER CODE BEGIN PM */</span><br><br><span class="hljs-comment">/* USER CODE END PM */</span><br><br><span class="hljs-comment">/* Private variables ---------------------------------------------------------*/</span><br><br><span class="hljs-comment">/* USER CODE BEGIN PV */</span><br><br><span class="hljs-comment">/* USER CODE END PV */</span><br><br><span class="hljs-comment">/* Private function prototypes -----------------------------------------------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">SystemClock_Config</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>;<br><span class="hljs-comment">/* USER CODE BEGIN PFP */</span><br><br><span class="hljs-comment">/* USER CODE END PFP */</span><br><br><span class="hljs-comment">/* Private user code ---------------------------------------------------------*/</span><br><span class="hljs-comment">/* USER CODE BEGIN 0 */</span><br><br><span class="hljs-comment">/* USER CODE END 0 */</span><br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">  * @brief  The application entry point.</span><br><span class="hljs-comment">  * @retval int</span><br><span class="hljs-comment">  */</span><br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{<br>  <span class="hljs-comment">/* USER CODE BEGIN 1 */</span><br><br>  <span class="hljs-comment">/* USER CODE END 1 */</span><br><br>  <span class="hljs-comment">/* MCU Configuration--------------------------------------------------------*/</span><br><br>  <span class="hljs-comment">/* Reset of all peripherals, Initializes the Flash interface and the Systick. */</span><br>  HAL_Init();<br><br>  <span class="hljs-comment">/* USER CODE BEGIN Init */</span><br>	delay_init(<span class="hljs-number">180</span>);<span class="hljs-comment">// 配置延时函数，参数是系统时钟频率</span><br>  <span class="hljs-comment">/* USER CODE END Init */</span><br><br>  <span class="hljs-comment">/* Configure the system clock */</span><br>  SystemClock_Config();<br><br>  <span class="hljs-comment">/* USER CODE BEGIN SysInit */</span><br><br>  <span class="hljs-comment">/* USER CODE END SysInit */</span><br><br>  <span class="hljs-comment">/* Initialize all configured peripherals */</span><br>  MX_GPIO_Init();<br>  <span class="hljs-comment">/* USER CODE BEGIN 2 */</span><br>  <span class="hljs-comment">// 在测试板中IO引脚输出高电平LED不亮，其他板子请参照原理图</span><br>  HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET);<br>  HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET);<br>  HAL_GPIO_WritePin(LED3_GPIO_Port,LED3_Pin,GPIO_PIN_SET);<br>  HAL_GPIO_WritePin(LED4_GPIO_Port,LED4_Pin,GPIO_PIN_SET);<br>  <span class="hljs-comment">/* USER CODE END 2 */</span><br><br>  <span class="hljs-comment">/* Infinite loop */</span><br>  <span class="hljs-comment">/* USER CODE BEGIN WHILE */</span><br>  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>)<br>  {<br>	  <span class="hljs-comment">//流水灯begin</span><br>	  HAL_GPIO_WritePin(LED4_GPIO_Port,LED4_Pin,GPIO_PIN_SET);<br>	HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_RESET);<br>	  delay_ms(<span class="hljs-number">200</span>);<br>	  HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET);<br>	  HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_RESET);<br>	  delay_ms(<span class="hljs-number">200</span>);<br>	  HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET);<br>	  HAL_GPIO_WritePin(LED3_GPIO_Port,LED3_Pin,GPIO_PIN_RESET);<br>	  delay_ms(<span class="hljs-number">200</span>);<br>	  HAL_GPIO_WritePin(LED3_GPIO_Port,LED3_Pin,GPIO_PIN_SET);<br>	  HAL_GPIO_WritePin(LED4_GPIO_Port,LED4_Pin,GPIO_PIN_RESET);<br>	  delay_ms(<span class="hljs-number">200</span>);<br>	  <span class="hljs-comment">//流水灯end</span><br>    <span class="hljs-comment">/* USER CODE END WHILE */</span><br>	  <br>    <span class="hljs-comment">/* USER CODE BEGIN 3 */</span><br>  }<br>  <span class="hljs-comment">/* USER CODE END 3 */</span><br>}<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">  * @brief System Clock Configuration</span><br><span class="hljs-comment">  * @retval None</span><br><span class="hljs-comment">  */</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">SystemClock_Config</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{<br>  RCC_OscInitTypeDef RCC_OscInitStruct = {<span class="hljs-number">0</span>};<br>  RCC_ClkInitTypeDef RCC_ClkInitStruct = {<span class="hljs-number">0</span>};<br><br>  <span class="hljs-comment">/** Configure the main internal regulator output voltage</span><br><span class="hljs-comment">  */</span><br>  __HAL_RCC_PWR_CLK_ENABLE();<br>  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);<br><br>  <span class="hljs-comment">/** Initializes the RCC Oscillators according to the specified parameters</span><br><span class="hljs-comment">  * in the RCC_OscInitTypeDef structure.</span><br><span class="hljs-comment">  */</span><br>  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;<br>  RCC_OscInitStruct.HSIState = RCC_HSI_ON;<br>  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;<br>  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;<br>  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;<br>  RCC_OscInitStruct.PLL.PLLM = <span class="hljs-number">8</span>;<br>  RCC_OscInitStruct.PLL.PLLN = <span class="hljs-number">180</span>;<br>  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;<br>  RCC_OscInitStruct.PLL.PLLQ = <span class="hljs-number">2</span>;<br>  RCC_OscInitStruct.PLL.PLLR = <span class="hljs-number">2</span>;<br>  <span class="hljs-keyword">if</span> (HAL_RCC_OscConfig(&amp;RCC_OscInitStruct) != HAL_OK)<br>  {<br>    Error_Handler();<br>  }<br><br>  <span class="hljs-comment">/** Activate the Over-Drive mode</span><br><span class="hljs-comment">  */</span><br>  <span class="hljs-keyword">if</span> (HAL_PWREx_EnableOverDrive() != HAL_OK)<br>  {<br>    Error_Handler();<br>  }<br><br>  <span class="hljs-comment">/** Initializes the CPU, AHB and APB buses clocks</span><br><span class="hljs-comment">  */</span><br>  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK<br>                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;<br>  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;<br>  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;<br>  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;<br>  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;<br><br>  <span class="hljs-keyword">if</span> (HAL_RCC_ClockConfig(&amp;RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)<br>  {<br>    Error_Handler();<br>  }<br>}<br><br><span class="hljs-comment">/* USER CODE BEGIN 4 */</span><br><br><span class="hljs-comment">/* USER CODE END 4 */</span><br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">  * @brief  This function is executed in case of error occurrence.</span><br><span class="hljs-comment">  * @retval None</span><br><span class="hljs-comment">  */</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">Error_Handler</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{<br>  <span class="hljs-comment">/* USER CODE BEGIN Error_Handler_Debug */</span><br>  <span class="hljs-comment">/* User can add his own implementation to report the HAL error return state */</span><br>  __disable_irq();<br>  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>)<br>  {<br>  }<br>  <span class="hljs-comment">/* USER CODE END Error_Handler_Debug */</span><br>}<br><br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span>  USE_FULL_ASSERT</span><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">  * @brief  Reports the name of the source file and the source line number</span><br><span class="hljs-comment">  *         where the assert_param error has occurred.</span><br><span class="hljs-comment">  * @param  file: pointer to the source file name</span><br><span class="hljs-comment">  * @param  line: assert_param error line source number</span><br><span class="hljs-comment">  * @retval None</span><br><span class="hljs-comment">  */</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">assert_failed</span><span class="hljs-params">(<span class="hljs-type">uint8_t</span> *file, <span class="hljs-type">uint32_t</span> line)</span><br>{<br>  <span class="hljs-comment">/* USER CODE BEGIN 6 */</span><br>  <span class="hljs-comment">/* User can add his own implementation to report the file name and line number,</span><br><span class="hljs-comment">     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */</span><br>  <span class="hljs-comment">/* USER CODE END 6 */</span><br>}<br><span class="hljs-meta">#<span class="hljs-keyword">endif</span> <span class="hljs-comment">/* USE_FULL_ASSERT */</span></span><br><br></code></pre></td></tr></table></figure>
<p>编译通过后烧录即可。</p>
<p>delay的实现参考正点原子的例程。</p>
<p>delay.c</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"delay.h"</span></span><br><span class="hljs-comment">////////////////////////////////////////////////////////////////////////////////// 	 </span><br><span class="hljs-comment">//如果使用ucos,则包括下面的头文件即可.</span><br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS</span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"includes.h"</span>					<span class="hljs-comment">//ucos 使用	  </span></span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br><span class="hljs-comment">//////////////////////////////////////////////////////////////////////////////////  </span><br><span class="hljs-comment">//本程序只供学习使用，未经作者许可，不得用于其它任何用途</span><br><span class="hljs-comment">//ALIENTEK STM32F407开发板</span><br><span class="hljs-comment">//使用SysTick的普通计数模式对延迟进行管理(支持ucosii/ucosiii)</span><br><span class="hljs-comment">//包括delay_us,delay_ms</span><br><span class="hljs-comment">//正点原子@ALIENTEK</span><br><span class="hljs-comment">//技术论坛:www.openedv.com</span><br><span class="hljs-comment">//创建日期:2017/4/6</span><br><span class="hljs-comment">//版本：V1.1</span><br><span class="hljs-comment">//版权所有，盗版必究。</span><br><span class="hljs-comment">//Copyright(C) 广州市星翼电子科技有限公司 2014-2024</span><br><span class="hljs-comment">//All rights reserved</span><br><span class="hljs-comment">//********************************************************************************</span><br><span class="hljs-comment">//修改说明</span><br><span class="hljs-comment">////////////////////////////////////////////////////////////////////////////////// </span><br><br><span class="hljs-type">static</span> <span class="hljs-type">uint32_t</span> fac_us=<span class="hljs-number">0</span>;							<span class="hljs-comment">//us延时倍乘数</span><br><br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS		</span><br>    <span class="hljs-type">static</span> <span class="hljs-type">uint16_t</span> fac_ms=<span class="hljs-number">0</span>;				        <span class="hljs-comment">//ms延时倍乘数,在os下,代表每个节拍的ms数</span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br><br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS							<span class="hljs-comment">//如果SYSTEM_SUPPORT_OS定义了,说明要支持OS了(不限于UCOS).</span></span><br><span class="hljs-comment">//当delay_us/delay_ms需要支持OS的时候需要三个与OS相关的宏定义和函数来支持</span><br><span class="hljs-comment">//首先是3个宏定义:</span><br><span class="hljs-comment">//delay_osrunning:用于表示OS当前是否正在运行,以决定是否可以使用相关函数</span><br><span class="hljs-comment">//delay_ostickspersec:用于表示OS设定的时钟节拍,delay_init将根据这个参数来初始哈systick</span><br><span class="hljs-comment">//delay_osintnesting:用于表示OS中断嵌套级别,因为中断里面不可以调度,delay_ms使用该参数来决定如何运行</span><br><span class="hljs-comment">//然后是3个函数:</span><br><span class="hljs-comment">//delay_osschedlock:用于锁定OS任务调度,禁止调度</span><br><span class="hljs-comment">//delay_osschedunlock:用于解锁OS任务调度,重新开启调度</span><br><span class="hljs-comment">//delay_ostimedly:用于OS延时,可以引起任务调度.</span><br><br><span class="hljs-comment">//本例程仅作UCOSII和UCOSIII的支持,其他OS,请自行参考着移植</span><br><span class="hljs-comment">//支持UCOSII</span><br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span> 	OS_CRITICAL_METHOD						<span class="hljs-comment">//OS_CRITICAL_METHOD定义了,说明要支持UCOSII				</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_osrunning		OSRunning			<span class="hljs-comment">//OS是否运行标记,0,不运行;1,在运行</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_ostickspersec	OS_TICKS_PER_SEC	<span class="hljs-comment">//OS时钟节拍,即每秒调度次数</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_osintnesting 	OSIntNesting		<span class="hljs-comment">//中断嵌套级别,即中断嵌套次数</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br><br><span class="hljs-comment">//支持UCOSIII</span><br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span> 	CPU_CFG_CRITICAL_METHOD					<span class="hljs-comment">//CPU_CFG_CRITICAL_METHOD定义了,说明要支持UCOSIII	</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_osrunning		OSRunning			<span class="hljs-comment">//OS是否运行标记,0,不运行;1,在运行</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_ostickspersec	OSCfg_TickRate_Hz	<span class="hljs-comment">//OS时钟节拍,即每秒调度次数</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> delay_osintnesting 	OSIntNestingCtr		<span class="hljs-comment">//中断嵌套级别,即中断嵌套次数</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br><br><br><span class="hljs-comment">//us级延时时,关闭任务调度(防止打断us级延迟)</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_osschedlock</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{<br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span> CPU_CFG_CRITICAL_METHOD   			<span class="hljs-comment">//使用UCOSIII</span></span><br>	OS_ERR err; <br>	OSSchedLock(&amp;err);						<span class="hljs-comment">//UCOSIII的方式,禁止调度，防止打断us延时</span><br><span class="hljs-meta">#<span class="hljs-keyword">else</span>										<span class="hljs-comment">//否则UCOSII</span></span><br>	OSSchedLock();							<span class="hljs-comment">//UCOSII的方式,禁止调度，防止打断us延时</span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br>}<br><br><span class="hljs-comment">//us级延时时,恢复任务调度</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_osschedunlock</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{	<br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span> CPU_CFG_CRITICAL_METHOD   			<span class="hljs-comment">//使用UCOSIII</span></span><br>	OS_ERR err; <br>	OSSchedUnlock(&amp;err);					<span class="hljs-comment">//UCOSIII的方式,恢复调度</span><br><span class="hljs-meta">#<span class="hljs-keyword">else</span>										<span class="hljs-comment">//否则UCOSII</span></span><br>	OSSchedUnlock();						<span class="hljs-comment">//UCOSII的方式,恢复调度</span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br>}<br><br><span class="hljs-comment">//调用OS自带的延时函数延时</span><br><span class="hljs-comment">//ticks:延时的节拍数</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_ostimedly</span><span class="hljs-params">(<span class="hljs-type">uint32_t</span> ticks)</span><br>{<br><span class="hljs-meta">#<span class="hljs-keyword">ifdef</span> CPU_CFG_CRITICAL_METHOD</span><br>	OS_ERR err; <br>	OSTimeDly(ticks,OS_OPT_TIME_PERIODIC,&amp;err); <span class="hljs-comment">//UCOSIII延时采用周期模式</span><br><span class="hljs-meta">#<span class="hljs-keyword">else</span></span><br>	OSTimeDly(ticks);						    <span class="hljs-comment">//UCOSII延时</span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span> </span><br>}<br> <br><span class="hljs-comment">//systick中断服务函数,使用OS时用到</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">SysTick_Handler</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>{	<br>    HAL_IncTick();<br>	<span class="hljs-keyword">if</span>(delay_osrunning==<span class="hljs-number">1</span>)					<span class="hljs-comment">//OS开始跑了,才执行正常的调度处理</span><br>	{<br>		OSIntEnter();						<span class="hljs-comment">//进入中断</span><br>		OSTimeTick();       				<span class="hljs-comment">//调用ucos的时钟服务程序               </span><br>		OSIntExit();       	 				<span class="hljs-comment">//触发任务切换软中断</span><br>	}<br>}<br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br>			   <br><span class="hljs-comment">//初始化延迟函数</span><br><span class="hljs-comment">//当使用ucos的时候,此函数会初始化ucos的时钟节拍</span><br><span class="hljs-comment">//SYSTICK的时钟固定为AHB时钟</span><br><span class="hljs-comment">//SYSCLK:系统时钟频率</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_init</span><span class="hljs-params">(<span class="hljs-type">uint16_t</span> SYSCLK)</span><br>{<br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS 						<span class="hljs-comment">//如果需要支持OS.</span></span><br>	<span class="hljs-type">uint32_t</span> reload;<br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br>    HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);<span class="hljs-comment">//SysTick频率为HCLK</span><br>	fac_us=SYSCLK;						<span class="hljs-comment">//不论是否使用OS,fac_us都需要使用</span><br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS 						<span class="hljs-comment">//如果需要支持OS.</span></span><br>	reload=SYSCLK;					    <span class="hljs-comment">//每秒钟的计数次数 单位为K	   </span><br>	reload*=<span class="hljs-number">1000000</span>/delay_ostickspersec;	<span class="hljs-comment">//根据delay_ostickspersec设定溢出时间</span><br>											<span class="hljs-comment">//reload为24位寄存器,最大值:16777216,在180M下,约合0.745s左右	</span><br>	fac_ms=<span class="hljs-number">1000</span>/delay_ostickspersec;		<span class="hljs-comment">//代表OS可以延时的最少单位	   </span><br>	SysTick-&gt;CTRL|=SysTick_CTRL_TICKINT_Msk;<span class="hljs-comment">//开启SYSTICK中断</span><br>	SysTick-&gt;LOAD=reload; 					<span class="hljs-comment">//每1/OS_TICKS_PER_SEC秒中断一次	</span><br>	SysTick-&gt;CTRL|=SysTick_CTRL_ENABLE_Msk; <span class="hljs-comment">//开启SYSTICK</span><br><span class="hljs-meta">#<span class="hljs-keyword">else</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br>}								    <br><br><span class="hljs-meta">#<span class="hljs-keyword">if</span> SYSTEM_SUPPORT_OS 						<span class="hljs-comment">//如果需要支持OS.</span></span><br><span class="hljs-comment">//延时nus</span><br><span class="hljs-comment">//nus:要延时的us数.	</span><br><span class="hljs-comment">//nus:0~190887435(最大值即2^32/fac_us@fac_us=22.5)	    								   </span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_us</span><span class="hljs-params">(<span class="hljs-type">uint32_t</span> nus)</span><br>{		<br>	<span class="hljs-type">uint32_t</span> ticks;<br>	<span class="hljs-type">uint32_t</span> told,tnow,tcnt=<span class="hljs-number">0</span>;<br>	<span class="hljs-type">uint32_t</span> reload=SysTick-&gt;LOAD;				<span class="hljs-comment">//LOAD的值	    	 </span><br>	ticks=nus*fac_us; 						<span class="hljs-comment">//需要的节拍数 </span><br>	delay_osschedlock();					<span class="hljs-comment">//阻止OS调度，防止打断us延时</span><br>	told=SysTick-&gt;VAL;        				<span class="hljs-comment">//刚进入时的计数器值</span><br>	<span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)<br>	{<br>		tnow=SysTick-&gt;VAL;	<br>		<span class="hljs-keyword">if</span>(tnow!=told)<br>		{	    <br>			<span class="hljs-keyword">if</span>(tnow&lt;told)tcnt+=told-tnow;	<span class="hljs-comment">//这里注意一下SYSTICK是一个递减的计数器就可以了.</span><br>			<span class="hljs-keyword">else</span> tcnt+=reload-tnow+told;	    <br>			told=tnow;<br>			<span class="hljs-keyword">if</span>(tcnt&gt;=ticks)<span class="hljs-keyword">break</span>;			<span class="hljs-comment">//时间超过/等于要延迟的时间,则退出.</span><br>		}  <br>	};<br>	delay_osschedunlock();					<span class="hljs-comment">//恢复OS调度											    </span><br>}  <br><span class="hljs-comment">//延时nms</span><br><span class="hljs-comment">//nms:要延时的ms数</span><br><span class="hljs-comment">//nms:0~65535</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_ms</span><span class="hljs-params">(<span class="hljs-type">uint16_t</span> nms)</span><br>{	<br>	<span class="hljs-keyword">if</span>(delay_osrunning&amp;&amp;delay_osintnesting==<span class="hljs-number">0</span>)<span class="hljs-comment">//如果OS已经在跑了,并且不是在中断里面(中断里面不能任务调度)	    </span><br>	{		 <br>		<span class="hljs-keyword">if</span>(nms&gt;=fac_ms)						<span class="hljs-comment">//延时的时间大于OS的最少时间周期 </span><br>		{ <br>   			delay_ostimedly(nms/fac_ms);	<span class="hljs-comment">//OS延时</span><br>		}<br>		nms%=fac_ms;						<span class="hljs-comment">//OS已经无法提供这么小的延时了,采用普通方式延时    </span><br>	}<br>	delay_us((<span class="hljs-type">uint32_t</span>)(nms*<span class="hljs-number">1000</span>));				<span class="hljs-comment">//普通方式延时</span><br>}<br><span class="hljs-meta">#<span class="hljs-keyword">else</span>  <span class="hljs-comment">//不用ucos时</span></span><br><br><span class="hljs-comment">//延时nus</span><br><span class="hljs-comment">//nus为要延时的us数.	</span><br><span class="hljs-comment">//nus:0~190887435(最大值即2^32/fac_us@fac_us=22.5)	 </span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_us</span><span class="hljs-params">(<span class="hljs-type">uint32_t</span> nus)</span><br>{		<br>	<span class="hljs-type">uint32_t</span> ticks;<br>	<span class="hljs-type">uint32_t</span> told,tnow,tcnt=<span class="hljs-number">0</span>;<br>	<span class="hljs-type">uint32_t</span> reload=SysTick-&gt;LOAD;				<span class="hljs-comment">//LOAD的值	    	 </span><br>	ticks=nus*fac_us; 						<span class="hljs-comment">//需要的节拍数 </span><br>	told=SysTick-&gt;VAL;        				<span class="hljs-comment">//刚进入时的计数器值</span><br>	<span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)<br>	{<br>		tnow=SysTick-&gt;VAL;	<br>		<span class="hljs-keyword">if</span>(tnow!=told)<br>		{	    <br>			<span class="hljs-keyword">if</span>(tnow&lt;told)tcnt+=told-tnow;	<span class="hljs-comment">//这里注意一下SYSTICK是一个递减的计数器就可以了.</span><br>			<span class="hljs-keyword">else</span> tcnt+=reload-tnow+told;	    <br>			told=tnow;<br>			<span class="hljs-keyword">if</span>(tcnt&gt;=ticks)<span class="hljs-keyword">break</span>;			<span class="hljs-comment">//时间超过/等于要延迟的时间,则退出.</span><br>		}  <br>	};<br>}<br><br><span class="hljs-comment">//延时nms</span><br><span class="hljs-comment">//nms:要延时的ms数</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_ms</span><span class="hljs-params">(<span class="hljs-type">uint16_t</span> nms)</span><br>{<br>	<span class="hljs-type">uint32_t</span> i;<br>	<span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>;i&lt;nms;i++) delay_us(<span class="hljs-number">1000</span>);<br>}<br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br></code></pre></td></tr></table></figure>
<p>delay.h</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> _DELAY_H</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> _DELAY_H	  </span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"main.h"</span></span><br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_init</span><span class="hljs-params">(<span class="hljs-type">uint16_t</span> SYSCLK)</span>;<br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_ms</span><span class="hljs-params">(<span class="hljs-type">uint16_t</span> nms)</span>;<br><span class="hljs-type">void</span> <span class="hljs-title function_">delay_us</span><span class="hljs-params">(<span class="hljs-type">uint32_t</span> nus)</span>;<br><span class="hljs-meta">#<span class="hljs-keyword">endif</span></span><br><br><br></code></pre></td></tr></table></figure>
<h2 id="工程源码内附stm32f446的原理图">工程源码（内附stm32f446的原理图）</h2>
<p>百度网盘</p>
<p>链接：https://pan.baidu.com/s/1enfsIci683wCs_zBuYtJSw?pwd=nxet</p>
<p>提取码：nxet</p>
<h2 id="实践任务">实践任务</h2>
<ol type="1">
<li>在源代码的基础上使得流水灯来回流动而不是单向流动</li>
<li>通过控制灯亮与灭的持续时间来控制灯的亮度，实现四个不同亮度的灯（原理与PWM相同）</li>
<li>(拓展)使用定时器中断来实现流水灯的效果</li>
</ol>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E4%B8%93%E6%A0%8F/" class="category-chain-item">嵌入式专栏</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%8D%95%E7%89%87%E6%9C%BA%E5%85%A5%E9%97%A8/" class="print-no-link">#单片机入门</a>
      
        <a href="/tags/STM32/" class="print-no-link">#STM32</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>STM32流水灯</div>
      <div>http://example.com/posts/2680/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>晓寒</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年10月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-cc-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/posts/46409/" title="STM32定时器中断">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">STM32定时器中断</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/posts/38785/" title="keil和STM32的部署">
                        <span class="hidden-mobile">keil和STM32的部署</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments">
      
  <script type="text/javascript">
    Fluid.utils.loadComments('#comments', function() {
      var light = 'github-light';
      var dark = 'github-dark';
      var schema = document.documentElement.getAttribute('data-user-color-scheme');
      if (schema === 'dark') {
        schema = dark;
      } else {
        schema = light;
      }
      window.UtterancesThemeLight = light;
      window.UtterancesThemeDark = dark;
      var s = document.createElement('script');
      s.setAttribute('src', 'https://utteranc.es/client.js');
      s.setAttribute('repo', 'Dion6850/Dion6850.github.io');
      s.setAttribute('issue-term', 'title');
      
      s.setAttribute('theme', schema);
      s.setAttribute('crossorigin', 'anonymous');
      document.getElementById('comments').appendChild(s);
    })
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/css/time.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    

  

</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


    <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
    <script>
        (function (window, document) {
            var typing = Fluid.plugins.typing;
            var subtitle = document.getElementById('subtitle');
            if (!subtitle || !typing) {
                return;
            }
            var text = subtitle.getAttribute('data-typed-text');
            
            typing(text);
            
        })(window, document);
    </script>
 


  
    
      <script  src="/js/img-lazyload.js" ></script>
    
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/5.0.0/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }

        Fluid.events.registerRefreshCallback(function() {
          if ('MathJax' in window && MathJax.startup.document && typeof MathJax.startup.document.state === 'function') {
            MathJax.startup.document.state(0);
            MathJax.texReset();
            MathJax.typeset();
            MathJax.typesetPromise();
          }
        });
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.2/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="/css/time.js"></script>
<script src="/css/huadong.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<!-- hexo injector body_end start --><script src="/js/backgroundize.js"></script><!-- hexo injector body_end end --></body>
</html>
